package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.SetmealDto;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealDish;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import com.itheima.common.MyException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/11/1 17:00
 */
@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

   @Autowired
   private SetmealDishService setmealDishService;



    /**
     * 添加setmeal和其关联的setmealDish表
     * @param setmealDto
     */
    @Transactional
    @Override
    public void saveSetmeal(SetmealDto setmealDto) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDto, setmeal);
        // 保存setmeal套餐
        save(setmeal);
        // 获取seatmealdish数据添加到表中
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmeal.getId());
            setmealDishService.save(setmealDish);
        }
    }

    /**
     * 删除套餐和套餐关联的菜品
     * @param ids
     */
    @Transactional
    @Override
    public void deleteById(List<Long> ids) {
        for (Long id : ids) {
            Setmeal setmeal = getById(id);
            if(setmeal.getStatus() == 1){
                throw new MyException("套餐启用状态，无法删除！");
            }
        }
        removeByIds(ids);
        for (Long id : ids) {
            LambdaQueryWrapper<SetmealDish> query = new LambdaQueryWrapper<>();
            query.eq(SetmealDish::getSetmealId, id);
            setmealDishService.remove(query);
        }

    }
}
